//
//  AppModel.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/10.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit

enum ModelError: Error {
    case message(String)
}

//TODO:转换模型
public func lgtDecode<T>(_ type: T.Type, param: [String:Any]) throws -> T where T: Decodable{
    guard let jsonData = lgtGetJsonData(with: param) else {
        throw ModelError.message("转换data失败")
    }
    
    guard let model = try? JSONDecoder().decode(type, from: jsonData) else {
        throw ModelError.message("转换模型失败\n\(param)")
    }
    
    
    //模型转换错误处理
//    do{
//        let dict:Dictionary<String, Any> = param["data"] as! Dictionary<String, Any>
//        let jsonData = lgtGetJsonData(with: dict) ?? Data.init()
//        let model:PostParamModel =  try JSONDecoder().decode(PostParamModel.self, from: jsonData)
//    }catch{
//        print(error)
//    }
    
    return model
}

//public func lgtDecode2<T>(_ type: T.Type,array:Array<Dictionary<String,Any>>) -> Array<T>{
////    guard let jsonData = lgtGetJsonData(with: param) else {
////        throw ModelError.message("转换data失败")
////    }
////    guard let model = try? JSONDecoder().decode(type, from: jsonData) else {
////        throw ModelError.message("转换模型失败")
////    }
////    return model
//    
//    for i in 0..<array.count{
//        let param:Dictionary<String,Any> = array[i]
//        guard let jsonData = lgtGetJsonData(with: param) else {
//            continue
//        }
//        guard let model = try? JSONDecoder().decode(type, from: jsonData) else {
//            continue
//        }
//        
//       // typeArray.append(contentsOf: model)
//    }
//    
//    var typeArray:Array<T> = Array<T>.init()
//    return typeArray
//}


//public func lgtDecode<T>(_ type: T.Type, array:Array<Dictionary<String,Any>>) -> Array<T>{
//
//    var typeArray:Array<T> = Array<T>.init()
//    for i in 0..<array.count{
//        let param:Dictionary<String,Any> = array[i]
//        guard let jsonData = lgtGetJsonData(with: param) else {
//            continue
//        }
//        guard let model = try? JSONDecoder().decode(type, from: jsonData) else {
//            continue
//        }
//       // typeArray.append(contentsOf: model)
//    }
//    return typeArray
//}


public func lgtGetJsonData(with param: Any)->Data?{
    if !JSONSerialization.isValidJSONObject(param) {
        return nil
    }
    guard let data = try? JSONSerialization.data(withJSONObject: param, options: []) else {
        return nil
    }
    return data
}

struct AppModel:Codable {
    static var share:AppModel?
    var bd_qq:String? = ""
    var bd_wx:String? = ""
    var client_id:Int? = 0
    var cs_qq:String? = ""
    var cs_wx:String? = ""
    var m_host:String? = ""
    var release_status:Int? 
    var share_app_id:String? = ""
    var share_app_secret:String? = ""
    var share_ios_app_id:String? = ""
    var share_ios_app_secret:String? = ""
    var appBadge:AppBadgeModel?
}
